import { Injectable } from '@angular/core';
import {
  CanActivate,
  CanActivateChild,
  CanLoad,
  Route,
  Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from "@angular/router";
import { UserService } from "user";

@Injectable()
export class AuthGuardService implements CanActivate, CanActivateChild, CanLoad {
  redirectUrl = "";

  constructor(private user: UserService, private router: Router) {
    this.user.loginStatusSub.subscribe((isLogined) => {
      if (isLogined && this.redirectUrl) {
        let to = this.redirectUrl;
        this.redirectUrl = undefined;
        router.navigateByUrl(to);
      }
    });
    this.user.tokenSub.subscribe((isToken) => {
      if (isToken === "Token" && this.redirectUrl) {
        let to = this.redirectUrl;
        this.redirectUrl = undefined;
        router.navigateByUrl(to);
      }
    });
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    console.debug("canActivate Guard: ");
    return this.checkIsLogined(state.url);
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    console.debug("canActivateChild Guard: ");
    return this.checkIsLogined(state.url);
  }

  canLoad(route: Route) {
    console.debug("CanLoad Guard: ");
    return true;
  }

  checkIsLogined(url: string) {
    // if (this.user.isLogined) { return true; }
    // this.redirectUrl = url;
    // this.user.setModal("login");
    // return this.user.isLogined;
    if (this.user.isLogined) {
      return true;
    }
    this.redirectUrl = url;
    this.user.tokenSub.subscribe((str) => {
      if (str === "Token" || str === "toLogin") {
        if (this.user.isToken) {
          return true;
        }
        this.user.setModal("login");
      }
    });
    return this.user.isLogined || this.user.isToken;
  }

}